package com.lry.basic.algorithm.common;

import java.util.LinkedList;
import java.util.Stack;

/**
 * @author:刘仁有
 * @desc:
 * @email:953506233@qq.com
 * @data:2019/11/30
 */
public class SimplifyPath {
    public static void main(String[] args) {
        System.out.println(new SimplifyPath().simplifyPath2("/a/./b/../../c/"));
    }
   //   /a/../../b/../c/d/
    public String simplifyPath2(String path) {
        Stack<String> stack = new Stack<>();
        for (String str:path.split("/")) {
            if("..".equals(str)){
                if(!stack.isEmpty())
                stack.pop();
            }else if(!"".equals(str)&&!".".equals(str)){
                stack.push(str);
            }
        }
        String result = "";
        for (String str:stack) {
            result += "/"+str;
        }
        return result==""?"/":result;
    }

        public String simplifyPath(String path) {
            path += '/';
            char[] chs = path.toCharArray();
            int top = -1;
            for (char c : chs) {
                if (top == -1 || c != '/') {
                    chs[++top] = c;
                    continue;
                }
                if (chs[top] == '/') {
                    continue;
                }
                if (chs[top] == '.' && chs[top - 1] == '/') {
                    top--;
                    continue;
                }
                if (chs[top] == '.' && chs[top - 1] == '.' && chs[top - 2] == '/') {
                    top -= 2;
                    while (top > 0 && chs[--top] != '/') ;
                    continue;
                }
                chs[++top] = c;
            }
            if (top > 0 && chs[top] == '/') top--;
            return new String(chs, 0, top + 1);
        }

}
